package com.xzj.admin.resource.analysis.config;

import com.xzj.admin.analysis.base.common.handle.CommonAbstractAnalysisHandle;
import com.xzj.admin.analysis.base.manage.MessageAnalysisFactory;
import com.xzj.admin.resource.analysis.domain.props.BaseProps;
import com.xzj.admin.resource.analysis.domain.props.CloudProps;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @program: xzj-admin
 * @ClassName: AsyncTaskConfig
 * @description: 异步线程池配置
 * @author: XiaZunJun
 * @create: 2024-11-04 15:25
 */
@Component
public class AsyncTaskConfig {

    @Resource
    private BaseProps baseProps;

    @Bean
    public Executor analysisTask() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //最大线程数
        executor.setMaxPoolSize(baseProps.getThread().getAnalysisNum());
        //核心线程数
        executor.setCorePoolSize(baseProps.getThread().getAnalysisNum());
        //任务队列的大小，使用默认最大值
        // executor.setQueueCapacity(10);
        //线程前缀名
        executor.setThreadNamePrefix("analysis-");
        //线程存活时间,使用默认60s
        // executor.setKeepAliveSeconds(30);
        /**
         * 拒绝处理策略
         * CallerRunsPolicy()：交由调用方线程运行，比如 main 线程。
         * AbortPolicy()：直接抛出异常。
         * DiscardPolicy()：直接丢弃。
         * DiscardOldestPolicy()：丢弃队列中最老的任务。
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //线程初始化
        executor.initialize();
        return executor;
    }

    @Bean
    public Executor pushTask() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //最大线程数
        executor.setMaxPoolSize(baseProps.getThread().getPushNum());
        //核心线程数
        executor.setCorePoolSize(baseProps.getThread().getPushNum());
        //任务队列的大小，使用默认最大值
        // executor.setQueueCapacity(10);
        //线程前缀名
        executor.setThreadNamePrefix("push-");
        //线程存活时间,使用默认60s
        // executor.setKeepAliveSeconds(30);
        /**
         * 拒绝处理策略
         * CallerRunsPolicy()：交由调用方线程运行，比如 main 线程。
         * AbortPolicy()：直接抛出异常。
         * DiscardPolicy()：直接丢弃。
         * DiscardOldestPolicy()：丢弃队列中最老的任务。
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //线程初始化
        executor.initialize();
        return executor;
    }

    @Bean
    public CommonAbstractAnalysisHandle analysisHandle() {
        CloudProps cloudProps = baseProps.getCloud();
        MessageAnalysisFactory.createHandle(cloudProps.getId(), cloudProps.getType());
        return MessageAnalysisFactory.analysisHandle(cloudProps.getId(), cloudProps.getType());
    }

}
